package cn.jyszn.wxb.controller.page;

import cn.jyszn.wxb.model.UserInfo;
import cn.jyszn.wxb.service.UserInfoService;
import cn.jyszn.wxb.utils.StringUtils;
import com.alibaba.fastjson.JSONObject;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * Created by yasser on 2016/8/9.
 */
@Controller
public class MainController {

    private Logger logger = LogManager.getLogger(this.getClass());

    @Autowired
    private UserInfoService userInfoService;


    @RequestMapping("/index")
    public String toMainView(HttpSession session){
        UserInfo user = (UserInfo) session.getAttribute("userInfo");
        if(user == null){
            return "redirect:login";
        }
        return "index";
    }

    /**
     * 跳转到login页面
     * @return
     */
    @RequestMapping("/login")
    public String toLoginView(){
        return "login";
    }

    /**
     * 进行执行登录
     * @param phone
     * @param password
     * @param request
     * @return
     */
    @RequestMapping(value = "/login/submit", method = RequestMethod.POST)
    public @ResponseBody JSONObject doLoginView(String phone, String password, HttpServletRequest request){
        JSONObject result = new JSONObject();
        if(StringUtils.isEmpty(phone, password)){
            result.put("status", -1);
            result.put("msg", "登录的手机或密码不能为空！");
            return result;
        }

        UserInfo userInfo = userInfoService.load(Long.valueOf(phone), StringUtils.getMD5Str(password));
        if(userInfo == null){
            result.put("status", 0);
            result.put("msg", "手机号或密码不正确！");
            return result;
        }
        // 将登录新存入session中
        request.getSession().setAttribute("userInfo", userInfo);
        result.put("status", 1);
        result.put("msg", "登录成功！");
        return result;
    }


    /**
     * 转向注册界面
     * @param parentId
     * @return
     */
    @RequestMapping("/register")
    public String toRegisterView(int parentId, String belongCode){
        logger.info("注册的parentId:" + parentId);
        logger.info("注册的belongCode:" + belongCode);
        return "register";
    }

    /**
     * 客户端提交手机号，向手机号发送验证码
     * @param phone
     * @param session
     * @return
     */
    @RequestMapping(value = "/register/phoneCode", method = RequestMethod.POST)
    public @ResponseBody JSONObject sendPhoneCode(String phone, HttpSession session){
        JSONObject result = new JSONObject();
        if(!StringUtils.validatePhone(phone)){
            result.put("status", -1);
            result.put("msg", "手机号不正确！");
            return result;
        }
        String phoneCode = "1234";
        session.setAttribute("phoneCode", phoneCode);
        logger.info("向手机号：" + phone + "发送的验证码是：" + phoneCode);
        result.put("status", 1);
        result.put("msg", "验证码已经发送！");
        return result;
    }

    /**
     * 处理注册提交的数据
     * @param userame
     * @param phone
     * @param cid
     * @param password
     * @param parentId
     * @param belongCode
     * @return
     */
    @RequestMapping(value = "/register/submit", method = RequestMethod.POST)
    public @ResponseBody JSONObject doRegisterSubmit(String username, String phone, String cid, int parentId, String belongCode){
        JSONObject result = new JSONObject();
        if(StringUtils.isEmpty(username, phone, cid)){
            result.put("status", -1);
            result.put("msg", "注册的数据不能为空！");
            return result;
        }
        UserInfo parentUser = userInfoService.load(parentId);
        if(parentUser == null){
            result.put("status", -1);
            result.put("msg", "注册参数异常！");
            return result;
        }
        int level = parentUser.getTreeLevel() + 1;
        int leftNum = parentUser.getRightNum();
        int rightNum = leftNum + 1;
        String password = cid.substring(14);// 将身份证后4位作为密码

        UserInfo userInfo = new UserInfo(username, StringUtils.getMD5Str(password),
                level,
                leftNum,
                rightNum,
                Long.valueOf(phone),
                cid,
                new Date().getTime(),
                parentId,
                (short) 0,
                belongCode);
        if(userInfoService.add(userInfo)){
            result.put("status", 1);
            result.put("msg", "注册成功！");
            return result;
        }
        result.put("status", 0);
        result.put("msg", "注册失败！");
        return result;
    }
}
